import numpy as np
import matplotlib.pyplot as plt

# 定义参数
fs = 10000  # 采样频率 (Hz)
t = np.linspace(0, 1, fs, endpoint=False)  # 时间向量，时长 1 秒

# 生成 50Hz 信号
f_signal = 50  # 信号频率 (Hz)
signal_50Hz = np.sin(2 * np.pi * f_signal * t)

# 生成白噪声
noise = np.random.normal(0, 0.1, t.shape)

# 生成 2000Hz 变频器白噪声
f_inverter = 2000  # 变频器频率 (Hz)
inverter_signal = np.sin(2 * np.pi * f_inverter * t)
inverter_noise = np.random.normal(0, 0.05, t.shape)
inverter_noisy_signal = inverter_signal + inverter_noise

# 叠加信号
final_signal = signal_50Hz + noise + inverter_noisy_signal

# 进行傅里叶变换
fourier_transform = np.fft.fft(final_signal)
# 获取频率轴
freqs = np.fft.fftfreq(len(final_signal), 1/fs)

# 取单边频谱并计算幅度（绝对值）
n = len(final_signal)
single_sided_fft = 2.0/n * np.abs(fourier_transform[:n//2])
single_sided_freqs = freqs[:n//2]

# 将幅度转换为 dB 模式
single_sided_fft_db = 20 * np.log10(single_sided_fft)

# 绘制时域信号
plt.figure(figsize=(12, 10))
plt.subplot(2, 1, 1)
plt.plot(t, final_signal, label='Final Signal')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Three - phase Motor Line Current Single - phase Waveform with Noise (Time Domain)')
plt.legend()
plt.grid(True)

# 绘制频域信号（dB 模式）
plt.subplot(2, 1, 2)
plt.plot(single_sided_freqs, single_sided_fft_db, label='Frequency Domain (dB)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude (dB)')
plt.title('Three - phase Motor Line Current Single - phase Waveform with Noise (Frequency Domain in dB)')
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()
